<template>
  <div>
    <div v-for="(item, index) in messageList" :key="index" class="top">
      <div style="display: flex; align-items: center">
        <h3>{{ $t('caseorder.yulan.yulan88') }}</h3>
        <div class="text">{{ item.content }}</div>
      </div>
      <div class="top-text">
        <el-row class="title_info">
          <div style="margin-top: 6px">
            <el-col
              v-if="item.fileList.length > 0"
              class="title_info_item"
              style="margin-bottom: 10px"
            >
              <div>
                <i style="font-size: 18px; margin-right: 3px" class="el-icon-paperclip"></i
                >{{ $t('caseorder.yulan.yulan89') }}：
              </div>
              <div
                v-for="(ite, ind) in item.fileList"
                :key="ind"
                class="dia-list"
                style="cursor: pointer; margin-right: 16px; line-height: 22px; padding-left: 50px"
              >
                <span style="margin-right: 20px" @click="download(ite)">{{ ite.fileName }}</span>
                <img
                  style="width: 13px"
                  src="@/assets/img/file_download.png"
                  alt=""
                  @click="download(ite)"
                />
                <!-- <i  class=" el-icon-download"></i> -->
              </div>
            </el-col>
          </div>
          <div>
            <el-col :span="3" class="title_info_item">
              <span>{{ $t('caseorder.yulan.yulan90') }}：</span>
              <span>{{ item.creatorName }}</span>
            </el-col>
            <el-col :span="8" class="title_info_item">
              <span>{{ $t('caseorder.yulan.yulan91') }}：</span>
              <span>{{ item.createDate }}</span>
            </el-col>
          </div>
        </el-row>
      </div>
    </div>

    <el-form :model="form" :rules="rules" ref="ruleForm">
      <el-form-item label="" prop="content">
        <div class="textarea">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 16 }"
            :placeholder="$t('caseorder.yulan.yulan92')"
          />
        </div>
      </el-form-item>

      <el-form-item label="" prop="fileList">
        <div class="bottom">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="10"
            :multiple="true"
            action=" "
            :on-change="handleFileChange"
            :on-remove="onRemove"
            :before-remove="beforeRemove"
            :on-exceed="fileExceed"
            :auto-upload="false"
            :file-list="fileList"
            :http-request="httpRequest"
          >
            <div class="add">
              <i style="font-size: 18px; margin-right: 3px" class="el-icon-paperclip"></i
              >{{ $t('caseorder.yulan.yulan93') }}
            </div>
          </el-upload>
          <div class="progress" v-if="isShowPercentag && uploadPercentage < 100">
            <span>{{ $t('versionManagement.uploadProgress') }}：</span>

            <el-progress
              :text-inside="true"
              :stroke-width="16"
              :percentage="uploadPercentage"
              text-color="#FFFFFF"
            >
            </el-progress>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button
              size="small"
              type="primary"
              @click="addMessage"
              :disabled="loading"
              :loading="loading"
              >{{ $t('caseorder.yulan.yulan94') }}</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  // 消息
  name: 'BLZMasterMessage',

  data() {
    return {
      form: {
        content: '',
        fileList: [],
      },
      rules: {
        content: [
          { required: true, message: this.$t('caseorder.anli141'), trigger: 'blur' },
        ],
      },
      textarea2: '',
      messageList: [],
      fileList: [],
      actionUrl: 'http://192.168.110.125:8090/renren-admin/tools/upload',
      // 回显附件列表
      fileList: [],
      // 上传附件列表
      files: [],
      isShowPercentag: false,
      uploadPercentage: 0,
      loading: false,
    };
  },

  mounted() {
    this.selectMessageList();
  },

  methods: {
    // 上传文件之前
    beforeUpload(file) {
      this.fileList.forEach((item) => {
        if (isEquael(item.fileName, file.name)) {
          return this.$message.warning(this.$t('caseorder.yulan.yulan95'));
        }
      });
      this.$refs.upload.submit();
    },
    // 上传发生变化钩子
    handleFileChange(file, fileList) {
      this.files = fileList;
      this.fileList.push(file);
    },
    // 文件个数超过最大限制时
    fileExceed(file, fileList) {
      if (this.fileList.length > 10) {
        this.$message.warning(this.$t('caseorder.yulan.yulan96'));
      }
    },
    // 删除前的钩子
    beforeRemove(file, fileList) {
      return this.$confirm(this.$t('caseorder.yulan.yulan97') + `${file.name}？`);
    },
    // 删除的钩子
    onRemove(file, fileList) {
      this.files = fileList;
    },
    handleChanged(file, fileList) {
      this.fileList = fileList;
      if (this.fileList.length == 0) {
        this.$message.error(this.$t('caseorder.yulan.yulan98'));
        return;
      }
      //   this.$refs.upload.submit();
    },
    httpRequest(opt) {
      this.uploadPercentage = 0;
      if (this.files.length === 0) {
        // return this.$message.warning(this.$t('caseorder.yulan.yulan99'))
        this.form.orderId = this.$route.query.id;
        this.$http
          .post('/orderMessage/addMessage', this.form)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              this.$message.success(this.$t('caseorder.yulan.yulan100'));
              this.form = {
                content: '',
                fileList: [],
              };
              this.fileList = [];
              this.files = [];
              this.selectMessageList();
              this.loading = false;
            }
          })
          .catch((err) => {
            console.log('err', err);
            this.loading = false;
          });
      } else {
        this.isShowPercentag = true;
        const formData = new FormData();
        this.files.forEach((file) => {
          formData.append('file', file.raw);
        });
        this.$http({
          url: '/tools/uploadMulti',
          method: 'post',
          data: formData,
          onUploadProgress: (progressEvent) => {
            this.uploadPercentage = ((progressEvent.loaded / progressEvent.total) * 100) | 0; //百分比
          },
        })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              const designFileUrl = [];
              const designFileName = [];
              this.form.fileList = res.data;
              this.form.fileList.forEach((item) => {
                item.url = item.filepath;
                item.fileName = item.oldName;
              });
              this.form.orderId = this.$route.query.id;
              this.$http
                .post('/orderMessage/addMessage', this.form)
                .then(({ data: res }) => {
                  if (res.code !== 0) {
                    return this.$message.error(res.msg);
                  } else {
                    this.$message.success(this.$t('caseorder.yulan.yulan100'));
                    this.form = {
                      content: '',
                      fileList: [],
                    };
                    this.fileList = [];
                    this.files = [];
                    this.selectMessageList();
                    this.loading = false;
                  }
                })
                .catch((err) => {
                  console.log('err', err);
                  this.loading = false;
                });
              // this.$message.success("上传成功")
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
      }
    },
    addMessage() {
      // if (!this.form.content) {
      //   return this.$message.error(this.$t('caseorder.yulan.yulan101'));
      // }

      this.$refs['ruleForm'].validate((valid) => {
        if(valid){
          this.loading = true;
          this.httpRequest();
        }
      });
     
    },
    selectMessageList() {
      this.$http
        .post(`/orderMessage/selectMessageList?orderId=${this.$route.query.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.messageList = [];
            this.messageList = res.data;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    downloadByBlob(url, name) {
      const image = new Image();
      image.setAttribute('crossOrigin', 'anonymous');
      image.src = url;
      image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height);
        console.lo;
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob);
          download(url, name);
          // 用完释放URL对象
          URL.revokeObjectURL(url);
        });
      };
    },
    download(val) {
      window.open(val.url);
      // if (val.url.includes(".jpg")) {
      //     console.log("1111111111", val.url, val.fileName)
      //     this.downloadByBlob(val.url, val.fileName)
      // } else {
      //     window.open(val.url);
      // }
      // window.location.href = url
    },
  },
};
</script>

<style lang="scss" scoped>
.top {
  width: 100%;
  padding: 10px 16px 16px 16px;
  background: #e5ebef;
  margin-bottom: 10px;

  .text {
    width: 90%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-left: 6px;
  }

  .top-text {
    margin-top: 10px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #666666;
    opacity: 1;
  }
}

.textarea {
  margin-top: 16px;
  margin-bottom: 0px;
}
.progress {
  margin: 10px 0px;
  span {
    display: inline-block;
    margin: 10px 0px;
  }
}
.bottom {
  .add {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 47px;
    color: #003e67;
    opacity: 1;
  }
}
</style>
